import Vue from "vue";
import router from "@/router";
const _ = require("lodash"); // lodash
import { asyncRoutes } from "@/router"; // 动态路由
import constantRoutes, { dashboardRoute } from "@/router/constantRouter.js"; // 静态路由
import { getRandomId, flattenDeepBy } from "@/utils";

// 递归插入自定义路由方法
const solveRouterList = (arr, customTree) => {
    let accessedRoutes = _.cloneDeep(arr);
    accessedRoutes.forEach(item => {
        // 对每个自定义路由进行查询，是否有存在的自定义路由父节点关联
        customTree.forEach(customRouter => {
            if (customRouter["parent_code"] === item.name && customRouter["status"] === 1 && customRouter["used_flag"] === 1) {
                const matchRouter = {
                    path: "dynamic-list-" + customRouter["menu_code"],
                    component: () => import("@/views/dynamicPages/list/index.vue"),
                    name: customRouter[MenuCode],
                    order: customRouter["menu_order"],
                    meta: { title: customRouter[MenuName] }
                };
                item.children.splice(customRouter["menu_order"] - 1, 0, matchRouter);
            }
        });
        // 如果该路由还有子路由，则继续对子路由处理
        if (item.children) {
            item.children = solveRouterList(item.children, customTree);
        }
    });
    return accessedRoutes;
};
// 排序方法
const sortRouter = (arr) => {
    arr.sort((a, b) => {
        return (a.order || 100) - (b.order || 100);
    });
    arr.forEach(i => {
        if (i.children) i.children = sortRouter(i.children);
    });
    return arr;
};

const state = {
    routes: [],
    addRoutes: [],
    firstMenu: [] // 当前一级菜单
};

const mutations = {
    // 储存路由结构
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes;
        state.routes = constantRoutes.concat(routes);
    },

    // 改变当前一级菜单
    SET_FIRST_MENU: (state, menu) => { state.firstMenu = menu; }
};

const actions = {
    /**
        * 根据获取的路由树, 生成对应路由
        * @param {Array} payload.rolesTree: 后端返回的当前用户的权限路由
        * @param {Array} payload.customTree: 后端返回的当前用户的自定义路由
        * @param {Array} asyncRoutes: 前端路由表
        */
    generateRoutes ({ commit }, payload) {
        const MenuCode = Vue.prototype.CONF.menuCode;
        const MenuName = Vue.prototype.CONF.menuName;
        // 一维化权限路由，并取状态为激活的路由
        let rolesTree = flattenDeepBy(payload.rolesTree, "children");
        // console.log("rolesTree:", rolesTree);
        // console.log("asyncRoutes:", asyncRoutes);
        const customTree = payload.customTree;
        return new Promise(resolve => {
            let accessedRoutes = [];
            // SETTING中打开了开发模式下，所有路由视为静态路由
            if (Vue.prototype.CONF.staticMode) accessedRoutes = _.clone(asyncRoutes);
            else {
                // 递归匹配权限路由
                const resolveRoutes = (asyncRoutesList) => {
                    const arr = [];
                    asyncRoutesList.forEach(asyncRoutesItem => {
                        const menu = rolesTree.find(rolesTreeItem => {
                            // console.log("rolesTreeItem[MenuCode]:", rolesTreeItem[MenuCode]);
                            return rolesTreeItem[MenuCode] === asyncRoutesItem.name;
                        });
                        // console.log("menu:", menu);
                        if (menu) {
                            // 若匹配到对应的权限路由，才将该路由写进路由表
                            if (asyncRoutesItem.children && _.isArray(asyncRoutesItem.children)) {
                                asyncRoutesItem.children = resolveRoutes(asyncRoutesItem.children);
                            }
                            asyncRoutesItem.meta.title = menu[MenuName];
                            asyncRoutesItem.order = menu["menuOrder"];
                            arr.push(asyncRoutesItem);
                        }
                        else if (asyncRoutesItem.whiteList) {
                            // 若该路由设置为白名单，则直接写入路由表(包括所有子路由)
                            arr.push(asyncRoutesItem);
                        }
                    });
                    // console.log("arr:", arr);
                    return arr;
                };
                accessedRoutes = resolveRoutes(_.cloneDeep(asyncRoutes));
                // 移除空的一级菜单
                accessedRoutes = accessedRoutes.filter(item => {
                    return item.children.length;
                });
            }

            // 插入自定义路由
            accessedRoutes = solveRouterList(accessedRoutes, customTree);
            // 排序菜单
            accessedRoutes = sortRouter(accessedRoutes);

            if (Vue.prototype.CONF.needDashboard) {
                // 如果需要首页, 则用下面的代码
                const dashboard = {
                    path: "/",
                    component: () => import("@/layout"),
                    redirect: "/dashboard",
                    name: "Dashboard",
                    meta: { title: "首页" },
                    children: [ dashboardRoute ]
                };
                accessedRoutes.unshift(dashboard);
            }
            else {
                /* 默认path: "/"指向第一个一级菜单下的二级(或三级)菜单 */
                const firstChildren = accessedRoutes[0].children[0];
                let activeMenuPath = "";
                if (firstChildren.children && firstChildren.children[0]) {
                    const subChildren = firstChildren.children[0];
                    activeMenuPath = accessedRoutes[0].path + "/" + firstChildren.path + "/" + subChildren.path;
                }
                else activeMenuPath = accessedRoutes[0].path + "/" + firstChildren.path ;
                const activeMenu = {
                    path: "/",
                    redirect: activeMenuPath,
                    hidden: true,
                    name: "DefaultPage",
                    meta: firstChildren.meta
                };
                accessedRoutes.unshift(activeMenu);
            }

            commit("SET_ROUTES", accessedRoutes || []);
            resolve(accessedRoutes || []);
        });
    },

    goFirstMenu ({ state }) {
        const f = JSON.parse(JSON.stringify(state.firstMenu));
        let menuArr = [];
        if (f.children) {
            f.children.forEach(item => {
                if (f.name !== "Dashboard") item.path = f.path + "/" + item.path;
            }); 
            menuArr = f.children;
        }
        if (menuArr[0]) {
            if (menuArr[0].children) {
                // 若第一个二级菜单有子菜单，则跳转子三级菜单
                router.push(menuArr[0].path + "/" + menuArr[0].children[0].path);
            }
            else {
                // 自动跳转到第一个二级菜单
                router.push(menuArr[0].path);
            }
        }
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
